"""
组织领域服务
实现组织领域的核心业务逻辑
"""

from typing import Optional, Dict, List, Tuple
from datetime import datetime
from app.domain.shared.base_service import DomainService
from .entities import (
    OrganizationOverview,
    EfficiencyAnalysis,
    TeamPerformance,
    CustomerAnalysis,
    Distribution
)
from app.domain.organization.data_processor import OrganizationDataProcessor
from app.infrastructure.database import DatabaseConnection
from app.config.database_config import DB_CONFIG
from app.infrastructure.api.api_client import api_client
from app.config.api_config import ORGANIZATION_INFO_DATA


class OrganizationDomainService(DomainService):
    """组织领域服务"""

    def __init__(self):
        self.data_processor = OrganizationDataProcessor()
        print(DB_CONFIG)
        self.db = DatabaseConnection(DB_CONFIG)
        self.api_client = api_client
        self.raw_data = None

    def get_total_comparison(self) -> Dict:
        """获取API和数据库的总人数对比"""
        try:
            # 获取API数据
            api_data = self.api_client.request(
                'POST',
                'api/tds-system/sysTemplate/dataView',
                json=ORGANIZATION_INFO_DATA
            )
            self.raw_data = api_data  # 保存原始数据供其他方法使用
            
            # 获取API总人数
            api_total = self._get_api_total_count()
            
            # 获取数据库总人数
            db_total = self._get_db_total_count()
            
            # 计算匹配率
            match_rate = self._calculate_match_rate(api_total, db_total)
            
            return {
                'api_total': api_total,
                'db_total': db_total,
                'match_rate': match_rate,
                'is_matched': abs(api_total - db_total) <= 1  # 允许1人的误差
            }
        except Exception as e:
            print(f"获取总人数对比数据失败: {str(e)}")
            return {
                'error': str(e),
                'api_total': 0,
                'db_total': 0,
                'match_rate': 0,
                'is_matched': False
            }

    def get_age_comparison(self) -> Dict:
        """获取API和数据库的年龄对比"""
        try:
            # 获取API年龄数据
            api_age_data = self._get_api_age_data()
            
            # 获取数据库年龄数据
            db_age_data = self._get_db_age_data()
            
            # 计算匹配率
            match_rate = self._calculate_distribution_match_rate(api_age_data, db_age_data)
            
            return {
                'api_data': api_age_data,
                'db_data': db_age_data,
                'match_rate': match_rate,
                'is_matched': match_rate >= 90  # 匹配率达到90%以上认为匹配
            }
        except Exception as e:
            print(f"获取年龄对比数据失败: {str(e)}")
            return {
                'error': str(e),
                'api_data': {},
                'db_data': {},
                'match_rate': 0,
                'is_matched': False
            }

    def get_rank_comparison(self) -> Dict:
        """获取API和数据库的职级分布对比"""
        try:
            # 获取API职级数据
            api_rank_data = self._get_api_rank_data()
            
            # 获取数据库职级数据
            db_rank_data = self._get_db_rank_data()
            
            # 计算匹配率
            match_rate = self._calculate_distribution_match_rate(api_rank_data, db_rank_data)
            
            return {
                'api_data': api_rank_data,
                'db_data': db_rank_data,
                'match_rate': match_rate,
                'is_matched': match_rate >= 90  # 匹配率达到90%以上认为匹配
            }
        except Exception as e:
            print(f"获取职级分布对比数据失败: {str(e)}")
            return {
                'error': str(e),
                'api_data': {},
                'db_data': {},
                'match_rate': 0,
                'is_matched': False
            }

    def _get_api_age_data(self) -> Dict:
        """从API获取年龄分布数据"""
        try:
            age_data = {}
            if self.raw_data and 'tagList' in self.raw_data:
                for tag_group in self.raw_data['tagList']:
                    if tag_group.get('code') == 'HXMB_ZZHX_RCFX_JGFX':
                        for tag in tag_group.get('tags', []):
                            if tag['name'] == '年龄分析':
                                for item in tag['value']:
                                    age_range = item[0]['value']
                                    count = int(item[1]['value'])
                                    age_data[age_range] = count
            return age_data
        except Exception as e:
            print(f"获取API年龄数据失败: {str(e)}")
            return {}

    def _get_db_age_data(self) -> Dict:
        """从数据库获取年龄分布数据"""
        try:
            sql = """
                SELECT 
                    CASE 
                        WHEN age BETWEEN 18 AND 25 THEN '18-25岁'
                        WHEN age BETWEEN 26 AND 35 THEN '26-35岁'
                        WHEN age BETWEEN 36 AND 45 THEN '36-45岁'
                        WHEN age BETWEEN 46 AND 55 THEN '46-55岁'
                        ELSE '55岁以上'
                    END as age_range,
                    COUNT(*) as count
                FROM per_main
                WHERE del_flag = 0
                GROUP BY age_range
                ORDER BY age_range
            """
            result = self.db.execute_query(sql)
            return {row['age_range']: row['count'] for row in result}
        except Exception as e:
            print(f"获取数据库年龄数据失败: {str(e)}")
            return {}

    def _get_api_rank_data(self) -> Dict:
        """从API获取职级分布数据"""
        try:
            rank_data = {}
            if self.raw_data and 'tagList' in self.raw_data:
                for tag_group in self.raw_data['tagList']:
                    if tag_group.get('code') == 'HXMB_ZZHX_RCFX_JGFX':
                        for tag in tag_group.get('tags', []):
                            if tag['name'] == '职级统计':
                                for item in tag['value']:
                                    rank = item[0]['value']
                                    count = int(item[1]['value'])
                                    rank_data[rank] = count
            return rank_data
        except Exception as e:
            print(f"获取API职级数据失败: {str(e)}")
            return {}

    def _get_db_rank_data(self) -> Dict:
        """从数据库获取职级分布数据"""
        try:
            sql = """
                SELECT level as rank, COUNT(*) as count
                FROM per_main
                WHERE del_flag = 0
                GROUP BY level
                ORDER BY level
            """
            result = self.db.execute_query(sql)
            return {row['rank']: row['count'] for row in result}
        except Exception as e:
            print(f"获取数据库职级数据失败: {str(e)}")
            return {}

    def _calculate_distribution_match_rate(self, data1: Dict, data2: Dict) -> float:
        """计算分布数据的匹配率"""
        try:
            if not data1 or not data2:
                return 0.0
                
            total_items = len(set(data1.keys()) | set(data2.keys()))
            matched_items = 0
            
            for key in set(data1.keys()) | set(data2.keys()):
                value1 = data1.get(key, 0)
                value2 = data2.get(key, 0)
                if value1 == value2:
                    matched_items += 1
                    
            return round((matched_items / total_items) * 100, 2)
        except Exception as e:
            print(f"计算分布匹配率失败: {str(e)}")
            return 0.0

    def _get_api_total_count(self) -> int:
        """从API数据中获取总人数"""
        try:
            overview_data = self._extract_overview_data(self.raw_data)
            return int(overview_data.get("总人数", 0))
        except Exception as e:
            print(f"获取API总人数失败: {str(e)}")
            return 0

    def _get_db_total_count(self) -> int:
        """从数据库中获取总人数"""
        try:
            sql = """
                SELECT COUNT(*) as total
                FROM per_main
                WHERE del_flag = 0
            """
            result = self.db.execute_query(sql)
            return int(result[0]['total']) if result else 0
        except Exception as e:
            print(f"获取数据库总人数失败: {str(e)}")
            return 0

    def _calculate_match_rate(self, count1: int, count2: int) -> float:
        """计算匹配率"""
        if count1 == 0 and count2 == 0:
            return 100.0
        elif count1 == 0 or count2 == 0:
            return 0.0
        
        min_count = min(count1, count2)
        max_count = max(count1, count2)
        return round((min_count / max_count) * 100, 2)

    def process_organization_data(self, raw_data: dict) -> Dict:
        """
        处理原始组织数据
        
        Args:
            raw_data: 原始数据
            
        Returns:
            处理后的组织数据
        """
        try:
            self.raw_data = raw_data  # 保存原始数据供其他方法使用
            processed_data = {}
            
            # 处理组织概览
            overview_data = self._extract_overview_data(raw_data)
            if overview_data:
                processed_data['overview'] = OrganizationOverview.from_dict(overview_data)
                
            # 处理人效分析
            efficiency_data = self._extract_efficiency_data(raw_data)
            if efficiency_data:
                processed_data['efficiency'] = EfficiencyAnalysis.from_dict(efficiency_data)
                
            # 处理团队业绩
            performance_data = self._extract_performance_data(raw_data)
            if performance_data:
                processed_data['performance'] = TeamPerformance.from_dict(
                    self.data_processor.process_tag_value(performance_data)
                )
                
            # 处理客群分析
            customer_data = self._extract_customer_data(raw_data)
            if customer_data:
                processed_data['customers'] = CustomerAnalysis.from_dict(
                    self.data_processor.process_tag_value(customer_data)
                )
                
            # 处理各种分布数据
            distributions = self._extract_distribution_data(raw_data)
            processed_data['distributions'] = distributions
                
            return processed_data
        except Exception as e:
            print(f"处理组织数据时出错: {str(e)}")
            return {}

    def _extract_overview_data(self, raw_data: dict) -> Dict:
        """提取组织概览数据"""
        try:
            overview_data = {}
            if 'tagList' in raw_data:
                for tag_group in raw_data['tagList']:
                    if tag_group.get('name') == '组织概览':
                        for tag in tag_group.get('tags', []):
                            overview_data[tag['name']] = tag['value']
            return overview_data
        except Exception as e:
            print(f"提取组织概览数据时出错: {str(e)}")
            return {}

    def _extract_efficiency_data(self, raw_data: dict) -> Dict:
        """提取人效分析数据"""
        try:
            efficiency_data = {}
            if 'tagList' in raw_data:
                for tag_group in raw_data['tagList']:
                    if tag_group.get('code') == 'RXFX':
                        for tag in tag_group.get('tags', []):
                            efficiency_data[tag['name']] = tag['value']
            return efficiency_data
        except Exception as e:
            print(f"提取人效分析数据时出错: {str(e)}")
            return {}

    def _extract_performance_data(self, raw_data: dict) -> list:
        """提取团队业绩数据"""
        try:
            if 'tagList' in raw_data:
                for tag_group in raw_data['tagList']:
                    if tag_group.get('code') == 'zzhx_rcfx_yjfx':
                        for tag in tag_group.get('tags', []):
                            if tag['name'] == '团队业绩':
                                return tag['value']
            return []
        except Exception as e:
            print(f"提取团队业绩数据时出错: {str(e)}")
            return []

    def _extract_customer_data(self, raw_data: dict) -> list:
        """提取客群分析数据"""
        try:
            if 'tagList' in raw_data:
                for tag_group in raw_data['tagList']:
                    if tag_group.get('code') == 'zzhx_rcfx_yjfx':
                        for tag in tag_group.get('tags', []):
                            if tag['name'] == '客群分析':
                                return tag['value']
            return []
        except Exception as e:
            print(f"提取客群分析数据时出错: {str(e)}")
            return []

    def _extract_distribution_data(self, raw_data: dict) -> Dict[str, Distribution]:
        """提取各种分布数据"""
        try:
            distributions = {}
            if 'tagList' in raw_data:
                for tag_group in raw_data['tagList']:
                    if tag_group.get('code') == 'HXMB_ZZHX_RCFX_JGFX':
                        for tag in tag_group.get('tags', []):
                            distribution_data = self.data_processor.process_distribution_data(tag['value'])
                            if distribution_data:
                                if tag['name'] == '职级统计':
                                    distributions['rank'] = Distribution.from_dict(distribution_data)
                                elif tag['name'] == '年龄分析':
                                    distributions['age'] = Distribution.from_dict(distribution_data)
                                elif tag['name'] == '全日制最高学历统计':
                                    distributions['education'] = Distribution.from_dict(distribution_data)
                                elif tag['name'] == '工作稳定性':
                                    distributions['work_stability'] = Distribution.from_dict(distribution_data)
                                elif tag['name'] == '人员类型汇总':
                                    distributions['employee_type'] = Distribution.from_dict(distribution_data)
                                # 添加总人数分布
                                if 'total' in distribution_data:
                                    distributions['total'] = Distribution.from_dict({'total': distribution_data['total']})
            return distributions
        except Exception as e:
            print(f"提取分布数据时出错: {str(e)}")
            return {}

# 创建全局单例实例
organization_service = OrganizationDomainService()